package com.hzcx.app.simplechat.ui.mine;

import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.base.BaseActivity;
import com.hzcx.app.simplechat.bean.UpLoadImgBean;
import com.hzcx.app.simplechat.event.EditUserInfoEvent;
import com.hzcx.app.simplechat.ui.mine.contract.EditUserInfoContract;
import com.hzcx.app.simplechat.ui.mine.dialog.EditUserNickNameDialog;
import com.hzcx.app.simplechat.ui.mine.event.EditUserInfoSuccesEvent;
import com.hzcx.app.simplechat.ui.mine.presenter.EditUserInfoPresenter;
import com.hzcx.app.simplechat.ui.publicui.PublicRoundDialog;
import com.hzcx.app.simplechat.ui.publicui.QrCodeActivity;
import com.hzcx.app.simplechat.ui.user.bean.CityListBean;
import com.hzcx.app.simplechat.ui.user.bean.UserInfoBean;
import com.hzcx.app.simplechat.ui.user.enums.SexEnum;
import com.hzcx.app.simplechat.util.UserInfoUtil;
import com.hzcx.app.simplechat.util.date.DateUtil;
import com.hzcx.app.simplechat.util.glide.GlideUtils;
import com.hzcx.app.simplechat.util.photo.PhotoUtil;
import com.hzcx.app.simplechat.util.picker.PickerUtil;
import com.hzcx.app.simplechat.util.toast.ToastUtils;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 用户信息页-编辑
 */
public class EditUserInfoActivity extends BaseActivity<EditUserInfoPresenter> implements OnResultCallbackListener<LocalMedia>, EditUserInfoContract.View {
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_title_right)
    ImageView ivTitleRight;
    @BindView(R.id.tv_head)
    TextView tvHead;
    @BindView(R.id.iv_head)
    ImageView ivHead;
    @BindView(R.id.tv_nick_name)
    TextView tvNickName;
    @BindView(R.id.tv_nick_name_value)
    TextView tvNickNameValue;
    @BindView(R.id.tv_user_id)
    TextView tvUserId;
    @BindView(R.id.tv_user_id_value)
    TextView tvUserIdValue;
    @BindView(R.id.tv_qrcode)
    TextView tvQrcode;
    @BindView(R.id.iv_qrcode)
    ImageView ivQrcode;
    @BindView(R.id.tv_sex)
    TextView tvSex;
    @BindView(R.id.tv_sex_value)
    TextView tvSexValue;
    @BindView(R.id.tv_bir)
    TextView tvBir;
    @BindView(R.id.tv_bir_value)
    TextView tvBirValue;
    @BindView(R.id.tv_city)
    TextView tvCity;
    @BindView(R.id.tv_city_value)
    TextView tvCityValue;
    @BindView(R.id.tv_sign)
    TextView tvSign;
    @BindView(R.id.tv_sign_value)
    TextView tvSignValue;

    private UserInfoBean userInfoBean;
    private List<CityListBean> cityData;

    @Override
    public int getLayout() {
        return R.layout.activity_edit_userinfo;
    }

    @Override
    public void initPresenter() {
        mPresenter = new EditUserInfoPresenter();
    }

    @Override
    public void initView() {
        tvTitle.setText("编辑资料");

        cityData = new ArrayList<>();
        tvUserId.setText(getResources().getString(R.string.app_name) + "号");
    }

    @Override
    public void initData() {

        userInfoBean = UserInfoUtil.getUserInfo();

        loadUser();

    }

    @OnClick({R.id.tv_nick_name, R.id.tv_nick_name_value, R.id.tv_user_id, R.id.tv_user_id_value, R.id.tv_qrcode, R.id.iv_qrcode, R.id.tv_sex,
            R.id.tv_sex_value, R.id.tv_sign, R.id.tv_sign_value, R.id.tv_bir, R.id.tv_bir_value, R.id.iv_head, R.id.tv_head, R.id.tv_city,
            R.id.tv_city_value})
    public void viewOnClick(View view) {
        switch (view.getId()) {
            case R.id.tv_nick_name: // 修改昵称
            case R.id.tv_nick_name_value:
                showNickNameDialog();
                break;

            case R.id.tv_user_id: // 修改用户ID
            case R.id.tv_user_id_value:
                showEditUserIdDialog();
                break;

            case R.id.tv_qrcode: // 我的二维码
            case R.id.iv_qrcode:
                startActivity(new Intent(this, QrCodeActivity.class));
                break;

            case R.id.tv_sex: // 性别
            case R.id.tv_sex_value:
                showSex();
                break;

            case R.id.tv_sign: // 签名
            case R.id.tv_sign_value:
                startActivity(new Intent(this, EditUserSignActivity.class));
                break;

            case R.id.tv_bir: // 生日
            case R.id.tv_bir_value:
                showBir();
                break;

            case R.id.iv_head: // 头像
            case R.id.tv_head:
                showHead();
                break;

            case R.id.tv_city: // 地区
            case R.id.tv_city_value:
                if (cityData == null || cityData.size() <= 0) {
                    mPresenter.getCityList(this);
                } else {
                    showCityDialog();
                }
                break;
        }
    }

    /**
     * 加载用户信息
     */
    private void loadUser() {
        GlideUtils.loadImgAsCircle(this, UserInfoUtil.getUserHead(), ivHead);
        tvNickNameValue.setText(UserInfoUtil.getUserNickName());
        tvUserIdValue.setText(UserInfoUtil.getUserNumber());
        if (UserInfoUtil.getUserSex().equals("G")) {
            tvSexValue.setText("女");
        } else if (UserInfoUtil.getUserSex().equals("M")) {
            tvSexValue.setText("男");
        } else {
            tvSexValue.setText("保密");
        }
        tvBirValue.setText(UserInfoUtil.getUserBir());
        tvCityValue.setText(UserInfoUtil.getUserAddress());
        tvSignValue.setText(UserInfoUtil.getUserSign());
    }

    /**
     * 修改昵称弹窗
     */
    private void showNickNameDialog() {

        EditUserNickNameDialog editUserNickNameDialog = new EditUserNickNameDialog(this, tvNickNameValue.getText().toString(),
                name -> {
                    if (userInfoBean == null) {
                        userInfoBean = UserInfoUtil.getUserInfo();
                    }
                    if (userInfoBean != null) {
                        userInfoBean.setNickname(name);
                    }
                    mPresenter.editUser(EditUserInfoActivity.this, userInfoBean);
                });

        editUserNickNameDialog.show();
    }

    /**
     * 修改用户ID提示
     */
    private void showEditUserIdDialog() {
        if (userInfoBean == null) {
            userInfoBean = UserInfoUtil.getUserInfo();
        }
        if (userInfoBean==null){
            ToastUtils.show("用户数据为空");
            return;
        }
        if (userInfoBean.getIs_number() == 1) {
            showConfirmDialog("提示", getResources().getString(R.string.app_name) + "号仅限修改一次，请谨慎修改，是否确定？", null, () -> {
                if (userInfoBean.getIs_number() != 1) {
                    showError("您已修改过" + getResources().getString(R.string.app_name) + "号，无法再次修改");
                    return;
                }
                startActivity(new Intent(EditUserInfoActivity.this, EditUserIdActivity.class));
            });
        } else {
            showTips("提示", "您已修改过" + getResources().getString(R.string.app_name) + "号，无法再次修改", null);
        }
    }


    /**
     * 修改用户ID及签名
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void editUserSignOrId(EditUserInfoEvent event) {
        if (event.getTag() == EditUserInfoEvent.TAG_USERID) {
            tvUserIdValue.setText(event.getContent());
            userInfoBean.setChatnumber(event.getContent());
            userInfoBean.setIs_number(0);
            UserInfoUtil.saveUser(userInfoBean);
            EventBus.getDefault().post(new EditUserInfoSuccesEvent());
        } else if (event.getTag() == EditUserInfoEvent.TAG_SIGN) {
            tvSignValue.setText(event.getContent());
            userInfoBean.setBio(event.getContent());
            UserInfoUtil.saveUser(userInfoBean);
            EventBus.getDefault().post(new EditUserInfoSuccesEvent());
        }
    }

    /**
     * 展示性别选择器
     */
    private void showSex() {
        PickerUtil.showSexPicker(this, (options1, options2, options3, v) -> {
            if (PickerUtil.getSexList().get(options1).equals("男")) {
                if (userInfoBean == null) {
                    userInfoBean = UserInfoUtil.getUserInfo();
                }
                if (userInfoBean != null) {
                    userInfoBean.setGender(SexEnum.SEX_BOY);
                }
            } else if (PickerUtil.getSexList().get(options1).equals("女")) {
                if (userInfoBean == null) {
                    userInfoBean = UserInfoUtil.getUserInfo();
                }
                if (userInfoBean != null) {
                    userInfoBean.setGender(SexEnum.SEX_GRIL);
                }
            } else {
                if (userInfoBean == null) {
                    userInfoBean = UserInfoUtil.getUserInfo();
                }
                if (userInfoBean != null) {
                    userInfoBean.setGender(PickerUtil.getSexList().get(options1));
                }
            }
            if (userInfoBean != null) {
                mPresenter.editUser(EditUserInfoActivity.this, userInfoBean);
            }
        });
    }

    /**
     * 展示日期选择器
     */
    private void showBir() {
        PickerUtil.showDatePicker(this, (date, v) -> {
            if (userInfoBean == null) {
                userInfoBean = UserInfoUtil.getUserInfo();
            }
            if (userInfoBean != null) {
                userInfoBean.setBirthday(DateUtil.getTimerPicker(date));
                mPresenter.editUser(EditUserInfoActivity.this, userInfoBean);
            }
        });
    }

    /**
     * 展示头像弹窗
     */
    private void showHead() {
        List<String> list = new ArrayList<>();
        list.add("拍照");
        list.add("相册");
        PublicRoundDialog roundDialog = new PublicRoundDialog(this, "请选择", list, (pos, menu) -> {
            switch (menu) {
                case "拍照":
                    PhotoUtil.showCameraByHead(EditUserInfoActivity.this, this);
                    break;

                case "相册":
                    PhotoUtil.showPhotoByHead(EditUserInfoActivity.this, this);
                    break;
            }
        });
        roundDialog.show();
    }

    /**
     * 拍照或相册返回
     *
     * @param result
     */
    @Override
    public void onResult(List<LocalMedia> result) {
        mPresenter.upLoadHead(this, PhotoUtil.getPath(result.get(0)));
    }

    @Override
    public void onCancel() {

    }

    /**
     * 修改用户信息成功
     */
    @Override
    public void editSuccess() {
        UserInfoUtil.saveUser(userInfoBean);
        showError("修改成功");
        EventBus.getDefault().post(new EditUserInfoSuccesEvent());
        loadUser();
    }

    /**
     * 头像上传成功
     *
     * @param data
     */
    @Override
    public void upLoadResult(UpLoadImgBean data) {
        if (userInfoBean == null) {
            userInfoBean = UserInfoUtil.getUserInfo();
        }
        if (userInfoBean != null) {
            userInfoBean.setAvatar(data.getUrl());
            mPresenter.editUser(this, userInfoBean);
        }
    }

    /**
     * 信息修改失败
     */
    @Override
    public void editFail() {
        userInfoBean = UserInfoUtil.getUserInfo();
    }

    /**
     * 城市列表获取成功
     *
     * @param data
     */
    @Override
    public void cityListResult(List<CityListBean> data) {
        try {
            cityData.clear();
            cityData.addAll(data);
            showCityDialog();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 展示地区选择弹窗
     */
    private void showCityDialog() {
        PickerUtil.showCityPicker(this, cityData, (options1, options2, options3, v) -> {
            try {
                tvCityValue.setText(cityData.get(options1).getName() + cityData.get(options1).getProvince().get(options2).getName()
                        + cityData.get(options1).getProvince().get(options2).getCity().get(options3).getName());
                userInfoBean.setArea(cityData.get(options1).getProvince().get(options2).getCity().get(options3).getName());
                userInfoBean.setArea_id(cityData.get(options1).getProvince().get(options2).getCity().get(options3).getId() + "");
                mPresenter.editUser(EditUserInfoActivity.this, userInfoBean);
            } catch (Exception e) {
                e.printStackTrace();
                showError("无法填写该城市");
            }
        });
    }
}
